package com.situ.web.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.web.common.ServerResponse;
import com.situ.web.entity.Course;
import com.situ.web.service.ICourseService;
import com.situ.web.service.impl.CourseServiceImpl;
import com.situ.web.util.JSONUtil;

import net.sf.json.JSONArray;

@WebServlet("/course")
public class CourseServlet extends HttpServlet{
	private ICourseService courseService = new CourseServiceImpl(); 
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//解决乱码问题
		resp.setContentType("text/html;charset=utf-8");
		req.setCharacterEncoding("utf-8");
		String method = req.getParameter("method");
		if (method == null || "".equals(method)) {
			method = "pageList";
		}
		switch (method) {
		case "selectCourse":
			selectCourse(req, resp);
			break;
		case "insertBanjiIdCourseId":
			insertBanjiIdCourseId(req, resp);
			break;
		default:
			break;
		}
	}
	private void insertBanjiIdCourseId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String banjiId = req.getParameter("banjiId");
		String courseId = req.getParameter("courseId");
		ServerResponse serverResponse = null;
		boolean isSuccess = courseService.insertBanjiIdCourseId(Integer.parseInt(banjiId),Integer.parseInt(courseId) );
		if (isSuccess) {
			serverResponse = ServerResponse.createSuccess("选课成功");
		}else {
			serverResponse = ServerResponse.createError("选课失败");
		}
		JSONUtil.obj2Json(resp, serverResponse);
		
	}
	private void selectCourse(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		ArrayList<Course> list = courseService.selectCourse();
		JSONArray jsonArray = JSONArray.fromObject(list);
		resp.getWriter().write(jsonArray.toString());
		
	}
}
